import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:overload_guard/services/api_service.dart';

import '../main.dart';

class OcrPage extends StatefulWidget {

  @override
  State<OcrPage> createState() => _OcrPageState();
}

class _OcrPageState extends State<OcrPage> {
  late CameraController _controller;
  late Future<void> _initializeControllerFuture;

  @override
  void initState() {
    super.initState();
    // To display the current output from the Camera,
    // create a CameraController.
    _controller = CameraController(
      // Get a specific camera from the list of available cameras.
      cameras[0],
      // Define the resolution to use.
      ResolutionPreset.medium,
    );

    // Next, initialize the controller. This returns a Future.
    _initializeControllerFuture = _controller.initialize();
  }

  @override
  void dispose() {
    // Dispose of the controller when the widget is disposed.
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('拍照识别')),
      // You must wait until the controller is initialized before displaying the
      // camera preview. Use a FutureBuilder to display a loading spinner until the
      // controller has finished initializing.
      body: FutureBuilder<void>(
        future: _initializeControllerFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            // If the Future is complete, display the preview.
            return Column(
              children: [
                CameraPreview(_controller),
                IconButton(
                    onPressed: () async {
                      // Take the Picture in a try / catch block. If anything goes wrong,
                      // catch the error.
                      try {
                        // Ensure that the camera is initialized.
                        await _initializeControllerFuture;

                        // Attempt to take a picture and get the file `image`
                        // where it was saved.
                        final image = await _controller.takePicture();

                        if (!context.mounted) return;

                        var croppedFile = await ImageCropper().cropImage(
                          sourcePath: image.path,
                          aspectRatioPresets: [
                            CropAspectRatioPreset.square,
                            CropAspectRatioPreset.ratio3x2,
                            CropAspectRatioPreset.original,
                            CropAspectRatioPreset.ratio4x3,
                            CropAspectRatioPreset.ratio16x9
                          ],
                          uiSettings: [
                            AndroidUiSettings(
                                toolbarTitle: 'Cropper',
                                toolbarColor: Colors.deepOrange,
                                toolbarWidgetColor: Colors.white,
                                initAspectRatio: CropAspectRatioPreset.original,
                                lockAspectRatio: false),
                            IOSUiSettings(
                              title: 'Cropper',
                            ),
                            WebUiSettings(
                              context: context,
                            ),
                          ],
                        );

                        if(croppedFile != null) {

                          String imageStr = await byteToBase64(await croppedFile.readAsBytes());

                          print('imageStr:$imageStr');

                          var result =
                          await APIService.baiduOcrAccurateBasic(image: imageStr);

                          print('result:$result');

                          String words = "";

                          if (result["words_result"] != null) {
                            List<dynamic> wordsList = result['words_result'];
                            String concatenatedString = '';

                            wordsList.forEach((wordMap) {
                              concatenatedString += wordMap['words'] + ' ';
                            });

                            // Remove trailing space
                            concatenatedString = concatenatedString.trim();

                            words = concatenatedString;
                          }

                          Get.back(result: words);
                        }


                      } catch (e) {
                        // If an error occurs, log the error to the console.
                        print(e);
                      }
                    },
                    icon: Icon(Icons.camera_alt, size: 60,))
              ],
            );
          } else {
            // Otherwise, display a loading indicator.
            return const Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}

Future<String> fileToBase64(File file) async {
  List<int> imageBytes = await file.readAsBytes();
  String base64Image = base64Encode(imageBytes);
  return Uri.encodeFull(base64Image);
}
Future<String> byteToBase64(Uint8List byte) async {
  String base64Image = base64Encode(byte);
  return Uri.encodeFull(base64Image);
}

/*
class CropPage extends StatefulWidget {
  const CropPage({
    required this.bytes,
    super.key,
  });

  final Uint8List bytes;

  @override
  State<CropPage> createState() => _CropPageState();
}

class _CropPageState extends State<CropPage> {
  late CropController _controller;
  CropMode _mode = CropMode.rect;
  double? _aspectRatio;

  @override
  void initState() {
    super.initState();
    _controller = CropController();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final secondaryColor = Theme.of(context).colorScheme.secondary;
    final cropPreview = CropPreview(
      controller: _controller,
      bytes: widget.bytes,
      mode: _mode,
      maskOptions: MaskOptions(aspectRatio: _aspectRatio),
      dragPointBuilder: (size, position) => CropDragPoint(
        size: size,
        color: secondaryColor,
      ),
    );
    return Scaffold(
      appBar: AppBar(title: const Text('截取识别范围')),
      body: Column(
        children: [
          switch (Platform.operatingSystem) {
            'macos' => Expanded(
              child: cropPreview,
            ),
            _ => cropPreview,
          },
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20),
            child: SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: () => unawaited(_cropImage(context)),
                child: const Text('截取'),
              ),
            ),
          ),
          const SizedBox(height: 20),
        ],
      ),
    );
  }

  Future<void> _cropImage(BuildContext context) async {
    final croppedBytes = await _controller.crop();
    if (context.mounted) {


      print('onpressed!!!');

      String imageStr = await byteToBase64(croppedBytes);

      print('imageStr:$imageStr');

      var result =
      await APIService.baiduOcrAccurateBasic(image: imageStr);

      print('result:$result');

      String words = "";

      if (result["words_result"] != null) {
        List<dynamic> wordsList = result['words_result'];
        String concatenatedString = '';

        wordsList.forEach((wordMap) {
          concatenatedString += wordMap['words'] + ' ';
        });

        // Remove trailing space
        concatenatedString = concatenatedString.trim();

        words = concatenatedString;
      }

      Get.back(result: words);
    }
  }
}*/
